<template>
  <Dialog v-model="dialogVisible" title="航班动态导入" width="400" z-index="9999">
    <!-- 新增的日期选择控件 -->
    <el-form ref="formRef" :model="form" label-width="100px" class="mb-4">
      <el-form-item
        label="选择日期"
        prop="date"
        :rules="[{ required: true, message: '请选择日期', trigger: 'change' }]"
      >
        <el-date-picker
          v-model="form.date"
          type="date"
          placeholder="选择日期"
          :disabled-date="disabledDate"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :data="uploadData"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="updateSupport" />
            是否覆盖已经存在的数据
          </div>
          <span>仅允许导入 xls、xlsx 格式文件。</span>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { getAccessToken, getTenantId } from '@/utils/auth'
import type { UploadProps, UploadRawFile } from 'element-plus'
import { ElForm } from 'element-plus'

defineOptions({ name: 'MachineNoImportForm' })
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formRef = ref<InstanceType<typeof ElForm>>()
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref<InstanceType<typeof ElUpload>>()

// 表单数据
const form = reactive({
  date: ''
})

const importUrl =
  import.meta.env.VITE_BASE_URL +
  import.meta.env.VITE_API_URL +
  '/distm/schedule-record/import/machineno'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref<UploadProps['fileList']>([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  // 重置表单
  form.date = ''
  formRef.value?.clearValidate()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 日期禁用逻辑
const disabledDate = (time: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)

  const dayAfterTomorrow = new Date(today)
  dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2)

  // 只能选择今天和明天
  return time < today || time >= dayAfterTomorrow
}

// 上传时携带的数据
const uploadData = reactive({
  get date() {
    return form.date
  },
  get updateSupport() {
    return updateSupport.value
  }
})

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return

  // 先校验表单
  formRef.value.validate((valid) => {
    if (!valid) {
      message.error('请检查必填项')
      return false
    }

    if (fileList.value.length === 0) {
      message.error('请上传文件')
      return false
    }

    // 提交请求
    uploadHeaders.value = {
      Authorization: 'Bearer ' + getAccessToken(),
      'tenant-id': getTenantId()
    }
    formLoading.value = true
    uploadRef.value!.submit()
  })
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  formLoading.value = false
  if (response.code !== 0) {
    message.error(response.msg || '上传失败')
    return
  }
  // 拼接提示语
  const data = response.data || {}
  let text = `上传成功数量：${data.createLogs || 0};`
  text += `更新成功数量：${data.updateLogs || 0};`

  message.success(text)
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (err: any): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 文件数超出提示 */
const handleExceed = (files: UploadRawFile[], uploadFiles: UploadRawFile[]) => {
  message.error('最多只能上传一个文件！')
}
</script>